package com.pcbly.web.components.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.pcbly.web.Constants;

public class ArchiveUtils {

	public synchronized static void writeMonthToFile(long bid, String month) {
		File archivesMonthsFile = new File(Constants.ROOTPATH
				+ "archives/archivesmonths-" + bid + ".txt");
		String monthText = "";
		try {
			monthText = FileUtils.readFileToString(archivesMonthsFile,
					Constants.CHARSET);
		} catch (IOException e) {
			monthText = "";
		}
		if (StringUtils.isBlank(monthText)) {
			monthText = month;
		} else {
			if (monthText.endsWith(",")) {
				monthText = monthText + month;
			} else {
				monthText = monthText + "," + month;
			}
		}
		try {
			FileUtils.writeStringToFile(archivesMonthsFile, monthText,
					Constants.CHARSET);
		} catch (IOException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}

	public static List<String> getArchivesMonths(long bid) {
		List<String> l = new ArrayList<String>();
		File archivesMonthsFile = new File(Constants.ROOTPATH
				+ "archives/archivesmonths-" + bid + ".txt");
		String month = "";
		try {
			month = FileUtils.readFileToString(archivesMonthsFile,
					Constants.CHARSET);
		} catch (IOException e) {
			return l;
		}
		String[] months = month.split(",");
		if (months.length > 0) {
			for (int i = (months.length - 1); i >= 0; i--) {
				if (StringUtils.isNotBlank(months[i])) {
					l.add(months[i]);
				}
			}
		}
		return l;
	}

	public static boolean ArchivesMonthInFile(long bid, String month) {
		List<String> l = getArchivesMonths(bid);
		for (String m : l) {
			if (m.equalsIgnoreCase(month)) {
				return true;
			}
		}
		return false;
	}

	public static String getArchivesPostMainListPath(long bid, String month) {
		StringBuffer sb = new StringBuffer();
		sb.append(Constants.ROOTPATH);
		sb.append(getArchivesPostMainListWebPath(bid, month));
		File ft = new File(sb.toString());
		if (!ft.exists()) {
			ft.mkdirs();
		}
		return sb.toString();
	}

	public static String getArchivesPostMainListWebPath(long bid, String month) {
		StringBuffer sb = new StringBuffer();
		sb.append("archives/");
		sb.append(bid);
		sb.append("/");
		sb.append(month);
		sb.append("/");
		return sb.toString();
	}

	public static String getArchivesPostTopicPath(long bid, String month,
			long posttime) {
		StringBuffer sb = new StringBuffer();
		sb.append(Constants.ROOTPATH);
		sb.append(getArchivesPostMainListWebPath(bid, month));
		sb.append(DateUtils.formatDate4(new Date(posttime)));
		sb.append("/");
		sb.append((posttime % 100));
		sb.append("/");
		File ft = new File(sb.toString());
		if (!ft.exists()) {
			ft.mkdirs();
		}
		return sb.toString();
	}

}
